package com.yang.sso.oauth.oauth.tokenStore.jwt;

import com.yang.sso.oauth.oauth.converter.CustomerAccessTokenConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.sql.DataSource;
import java.security.KeyPair;

/**
 * @author: Islands
 * @create: 2024-04-11 21:38
 */

@Configuration
public class JwtTokenConfig {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private CustomerAccessTokenConverter customerAccessTokenConverter;



    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public KeyProperties keyProperties(){
        return new KeyProperties();
    }


    /**
     * 使用非对称加密算法对token签名
     */
    @Bean
    @Primary
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        //自定义用户身份转换
        DefaultAccessTokenConverter accessTokenConverter = (DefaultAccessTokenConverter) converter.getAccessTokenConverter();
        accessTokenConverter.setUserTokenConverter(customerAccessTokenConverter);
        return converter;
    }

    /**
     * 密钥库中获取密钥对(公钥+私钥)
     */
    @Bean
    public KeyPair keyPair() {
        KeyProperties.KeyStore keyStore = keyProperties().getKeyStore();
        // 导入证书
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(keyStore.getLocation(),
                keyStore.getSecret().toCharArray());
        try {
            return factory.getKeyPair(keyStore.getAlias(), keyStore.getPassword().toCharArray());
        }catch (RuntimeException  e){
            e.printStackTrace();
            return null;
        }
    }




    /**
     * 授权吗储存位置
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * 已授权用户信息
     * @return
     */
    @Bean
    public JdbcApprovalStore approvalStore() {
        return new JdbcApprovalStore(dataSource);
    }
}
